package com.ionehe.group.common.file.ex.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;

/**
 * 初始化sql脚本
 * @author 2022/1/14 <a href="mailto:a@ionehe.com">xiu</a>
 */
@Configuration
@Slf4j
public class FileExInitDatabaseConfiguration {

    @javax.annotation.Resource(name = "fileExDataSource")
    private DataSource dataSource;

    @Value("classpath:f_ct.sql")
    private Resource schemaScript;

    @Bean("fileExDBInitializer")
    @DependsOn("fileExDataSource")
    public DataSourceInitializer initDataSourceInitializer() {
        final DataSourceInitializer initializer = new DataSourceInitializer();
        initializer.setDataSource(dataSource);
        initializer.setDatabasePopulator(databasePopulator());
        return initializer;
    }

    private DatabasePopulator databasePopulator() {
        log.info("Initializing fileEx tables");
        long start = System.currentTimeMillis();

        final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(schemaScript);

        long end = System.currentTimeMillis();
        log.info("FileEx tables: initialization completed in {} ms", end - start);
        return populator;
    }
}